package com.milepost.workflow.assignee.ctrl;

import com.milepost.workflow.assignee.service.AssigneeService;
import com.milepost.workflow.assignee.vo.ZTreeNode;
import com.milepost.workflow.common.enums.DsKeyEnum;
import com.milepost.workflow.config.dynamicDs.DataSourceContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huarf
 * @Description
 * @create 2022-03-24 1:26
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/assignee")
public class AssigneeCtrl {

    private final AssigneeService assigneeService;

    private final FindByIndexNameSessionRepository<? extends Session> sessionRepository;

    /**
     * 根据部门id获取办理人数据
     *
     * @param deptId
     * @return
     */
    @GetMapping("/getSubNodesByDeptId")
    public List<ZTreeNode> getSubNodesByDeptId(
            @RequestParam(value = "deptId", required = false, defaultValue = "") String deptId,
            @RequestParam(value = "userName", required = false, defaultValue = "") String userName,
            HttpSession httpSession
    ) {

        List<ZTreeNode> response = null;

        try {
            //获取session对象
            String sessionId = httpSession.getId();
            Session session = sessionRepository.findById(sessionId);

            DataSourceContextHolder.setDataSource(DsKeyEnum.USER.getKey());
            List<ZTreeNode> zTreeNodeList = assigneeService.getSubNodesByDeptId(deptId, userName);
            response = zTreeNodeList;
        } catch (Exception e) {
            log.error("根据部门id获取办理人数据异常", e);
            response = new ArrayList<>();
        } finally {
            DataSourceContextHolder.clearDataSource();
        }

        return response;
    }

}
